# -*- coding:utf-8 -*-
import os
from collections import OrderedDict
import sys
import xlwt
import json
from colored import color

inputPath = sys.argv[1]
print('操作Json：', inputPath)

exportPath = "./export/"
""" 加载json"""

jsonData = OrderedDict()  # 有序字典 # 用于存储Json数据
with open(inputPath, 'r', encoding='UTF-8') as fr:
    jsonData = json.load(fr)

# print(jsonData)             # 结果

workbook = xlwt.Workbook()  # 创建一个excel对象

style = xlwt.XFStyle()  # 格式信息
font = xlwt.Font()  # 字体基本设置
font.name = u'宋体'
font.color = 'black'
font.height = 220  # 字体大小，220就是11号字体，大概就是11*20得来的吧
style.font = font
alignment = xlwt.Alignment()  # 设置字体在单元格的位置
alignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平方向
alignment.vert = xlwt.Alignment.VERT_CENTER  # 竖直方向
style.alignment = alignment
border = xlwt.Borders()  # 给单元格加框线
border.left = xlwt.Borders.THIN  # 左
border.top = xlwt.Borders.THIN  # 上
border.right = xlwt.Borders.THIN  # 右
border.bottom = xlwt.Borders.THIN  # 下
border.left_colour = 0x40  # 设置框线颜色，0x40是黑色，颜色真的巨多，都晕了
border.right_colour = 0x40
border.top_colour = 0x40
border.bottom_colour = 0x40
style.borders = border

""" 获取所有sheet名称"""


def findSheets():

    # 查找sheet
    sheets = jsonData.keys()
    for key in sheets:
        print("sheet::" + key)
        sheet = workbook.add_sheet(key, cell_overwrite_ok=True)  # 添加一个sheet页
        data = jsonData[key]
        writeSheet(sheet, data)

    # 保存
    (filepath, tempfilename) = os.path.split(inputPath)
    (filename, extension) = os.path.splitext(tempfilename)
    workbook.save(exportPath + filename + '.xls')


""" 类型转换"""


#判断变量类型的函数
def typeof(variate):
    type=None
    if isinstance(variate,int):
        type = "int"
    elif isinstance(variate,str):
        type = "str"
    elif isinstance(variate,float):
        type = "float"
    elif isinstance(variate,list):
        type = "list"
    elif isinstance(variate,tuple):
        type = "tuple"
    elif isinstance(variate,dict):
        type = "dict"
    elif isinstance(variate,set):
        type = "set"
    return type


    

def convertType(value):
    vtype = typeof(value)
    # print(vtype)
    if vtype == 'int':
        value = value and int(value) or 0
    elif vtype == 'float':
        value = value and float(value) or 0
    elif vtype == 'str':
        value = value and str(value) or ""
    elif vtype == 'list':
        value = value and json.dumps(value, ensure_ascii=False) or "[]"
    elif vtype == 'dict':
        value = value and json.dumps(value, ensure_ascii=False) or "{}"
        pass

    return value


""" 通过json字典转换成sheet"""


# json格式 {key:{id:value,name:value,...},key:{id:value},...}
def writeSheet(sheet, data):
    "readSheet"
    keys = list(data.keys())
    # title
    title = list(data[keys[0]].keys())
    sheet.write(0, 0, "id")  # 将title数组中的字段写入到0行i列中
    for t in range(len(title)):
        sheet.write(0, t+1, title[t])  # 将title数组中的字段写入到0行i列中

    for keyi in range(0, len(keys)):
        key = keys[keyi]
        line = list(data[key].keys())
        sheet.write(keyi+1, 0, keyi+1)
        for i in range(len(line)):
            value = data[key][line[i]]
            value = convertType(value)
            sheet.write(keyi+1, i+1, value)


findSheets()
